import Taro from '@tarojs/taro'
import { useState, memo } from 'react'
import { connect } from 'react-redux'
import { Button, Image, View } from '@tarojs/components'
import { Dialog, User } from '@/components/index'
import { ossUrl } from '@/utils/config'
import { getLoginCode } from '@/utils'
import { setUser } from '@/actions/user'
import { wxLogin } from '@/api/index'
import './index.scss'

const Login = ({ userInfo, setUserInfo }) => {
  const [show, setShow] = useState(false)
  /** 获取用户信息并且登录 */
  const getWxUserInfo = async () => {
    try {
      const user = await wxLogin()
      console.log(user, 'user')
      setUserInfo(user)
      Taro.showToast({ title: '登陆成功', icon: 'success' })
      setShow(false)
    } catch (error) {
      Taro.showToast({ icon: 'error', title: '登录失败请重试' })
      console.log(error, 'wxLogin 错误')
      getLoginCode()
    }
  }
  return (
    <View className='login'>
      <User userInfo={userInfo} open={() => setShow(true)} />
      {/* 登录的弹框 */}
      <Dialog show={show} close={() => setShow(!show)} customClass='login_dialog text_center'>
        <View className='text_center size_900 size_32 mg_b_30'>您还未登录</View>
        <View className='desc text_center size_24 lh_1d6 mg_0_auto mg_b_30'>登录后，你将得到更有针对性的发音能力档案。</View>
        <Image src={ossUrl + '/welcome_main.png'} className='welcome mg_0_auto'></Image>
        <View className='btn_wrapper flex mg_0_auto mg_t_24'>
          <Button className='btn reject cor_main bg_fff flex_center size_28 mg_none flex_1' onClick={() => setShow(!show)}>暂不登录</Button>
          <Button className='btn resolve cor_fff bg_main flex_center size_28 mg_none flex_1' onClick={getWxUserInfo}>立即登录</Button>
        </View>
      </Dialog>
    </View>
  )
}
const mapStateToProps = ({ user }) => ({
  userInfo: user.userInfo
});

const mapDispatchToProps = dispatch => ({
  setUserInfo(userInfo) {
    dispatch(setUser(userInfo))
  }
})

export default connect(mapStateToProps, mapDispatchToProps)(memo(Login))
